<script>
  //声明一条树形数据

  //数据中都会有id和 parentId进行相互对应
  let tree = [
    {
      id: 1,
      name: "北京",
      parentId: 0,
    },
    {
      id: 2,
      name: "江苏",
      parentId: 0,
      children: [
        {
          id: 4,
          name: "南京",
          parentId: 2,
        },
        {
          id: 5,
          name: "徐州",
          parentId: 2,
        },
        {
          id: 6,
          name: "扬州",
          parentId: 2,
        },
      ],
    },
    {
      id: 3,
      name: "安徽",
      parentId: 0,
      children: [
        {
          id: 7,
          name: "滁州",
          parentId: 3,
          children: [
            {
              id: 9,
              name: "汊河",
              parentId: 7,
            },
          ],
        },
        {
          id: 8,
          name: "合肥",
          parentId: 3,
        },
      ],
    },
  ];

  //声明一个函数，专门将树形换成扁平数据

  //attr子节点的字段
  function flatTree(data, attr = "children") {
    let flatArr = [];

    //recursion 递归处理函数
    function recursion(arr) {
      //遍历数组
      arr.forEach((item) => {
        // console.log(item);
        //判断自己是否有子节点
        if (item[attr] && item[attr].length > 0) {
          recursion(item[attr]);
        }
        //过滤掉子节点属性
        let keys = Object.keys(item);
        keys = keys.filter((key) => key !== attr);
        // console.log(keys);

        //重新声明一个对象。将item对应的公共属性添加到这个对象里面
        let obj = {};
        keys.forEach((key) => {
          obj[key] = item[key];
        });

        flatArr.push(obj);
        // console.log(obj);
      });
    }
    recursion(data);
    return flatArr;
  }
  let res = flatTree(tree);
  console.log(res);
</script>
